import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/login'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import Article from '@/views/Article'
import Publish from '@/views/Publish'
import { getItem } from '@/utils/auth.js'
// 进度条组件导入
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const Login = () => import('@/views/login')

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Layout,
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 前置守卫
// 限制用户登录及切换页面
router.beforeEach((to, from, next) => {
  Nprogress.start()
  if (getItem()) {
    if (to.path.toLowerCase() === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    if (to.path.toLowerCase() === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})
// // 后置守卫
router.afterEach((to, from) => {
  Nprogress.done()
})

export default router
